<template>
  <div class="statistics-reports-container">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-left">
        <h2>统计报表</h2>
        <p>审批流程的数据统计与分析报表</p>
      </div>
      <div class="header-right">
        <el-button type="primary" @click="generateReport">
          <el-icon><Document /></el-icon>
          生成报表
        </el-button>
        <el-button @click="exportReport">
          <el-icon><Download /></el-icon>
          导出报表
        </el-button>
      </div>
    </div>

    <!-- 时间范围选择 -->
    <div class="time-range-section">
      <div class="range-selector">
        <el-radio-group v-model="timeRange" @change="onTimeRangeChange">
          <el-radio-button label="today">今日</el-radio-button>
          <el-radio-button label="week">本周</el-radio-button>
          <el-radio-button label="month">本月</el-radio-button>
          <el-radio-button label="quarter">本季度</el-radio-button>
          <el-radio-button label="year">本年</el-radio-button>
          <el-radio-button label="custom">自定义</el-radio-button>
        </el-radio-group>
        <el-date-picker
          v-if="timeRange === 'custom'"
          v-model="customDateRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          style="margin-left: 15px;"
          @change="onCustomDateChange"
        ></el-date-picker>
      </div>
    </div>

    <!-- 核心指标卡片 -->
    <div class="key-metrics">
      <div class="metric-card total">
        <div class="metric-icon">
          <el-icon><Files /></el-icon>
        </div>
        <div class="metric-content">
          <div class="metric-number">{{ totalApplications }}</div>
          <div class="metric-label">总申请数</div>
          <div class="metric-change positive">+{{ totalApplicationsChange }}%</div>
        </div>
      </div>
      
      <div class="metric-card approved">
        <div class="metric-icon">
          <el-icon><Check /></el-icon>
        </div>
        <div class="metric-content">
          <div class="metric-number">{{ approvedApplications }}</div>
          <div class="metric-label">已通过</div>
          <div class="metric-change positive">+{{ approvedApplicationsChange }}%</div>
        </div>
      </div>
      
      <div class="metric-card rejected">
        <div class="metric-icon">
          <el-icon><Close /></el-icon>
        </div>
        <div class="metric-content">
          <div class="metric-number">{{ rejectedApplications }}</div>
          <div class="metric-label">已拒绝</div>
          <div class="metric-change negative">{{ rejectedApplicationsChange }}%</div>
        </div>
      </div>
      
      <div class="metric-card efficiency">
        <div class="metric-icon">
          <el-icon><TrendCharts /></el-icon>
        </div>
        <div class="metric-content">
          <div class="metric-number">{{ approvalEfficiency }}%</div>
          <div class="metric-label">审批效率</div>
          <div class="metric-change positive">+{{ approvalEfficiencyChange }}%</div>
        </div>
      </div>
    </div>

    <!-- 图表区域 -->
    <div class="charts-section">
      <!-- 申请趋势图 -->
      <div class="chart-container large">
        <div class="chart-header">
          <h3>申请趋势分析</h3>
          <el-select v-model="trendChartType" style="width: 120px;">
            <el-option label="按天" value="day"></el-option>
            <el-option label="按周" value="week"></el-option>
            <el-option label="按月" value="month"></el-option>
          </el-select>
        </div>
        <div class="chart-content" ref="trendChart" style="height: 350px;"></div>
      </div>
      
      <!-- 申请类型分布 -->
      <div class="chart-container medium">
        <div class="chart-header">
          <h3>申请类型分布</h3>
        </div>
        <div class="chart-content" ref="typeDistributionChart" style="height: 350px;"></div>
      </div>
      
      <!-- 审批状态分布 -->
      <div class="chart-container medium">
        <div class="chart-header">
          <h3>审批状态分布</h3>
        </div>
        <div class="chart-content" ref="statusDistributionChart" style="height: 350px;"></div>
      </div>
      
      <!-- 部门申请统计 -->
      <div class="chart-container large">
        <div class="chart-header">
          <h3>部门申请统计</h3>
          <el-select v-model="departmentChartType" style="width: 120px;">
            <el-option label="申请数量" value="count"></el-option>
            <el-option label="通过率" value="rate"></el-option>
            <el-option label="平均时长" value="duration"></el-option>
          </el-select>
        </div>
        <div class="chart-content" ref="departmentChart" style="height: 350px;"></div>
      </div>
      
      <!-- 审批时长分析 -->
      <div class="chart-container large">
        <div class="chart-header">
          <h3>审批时长分析</h3>
        </div>
        <div class="chart-content" ref="durationChart" style="height: 350px;"></div>
      </div>
      
      <!-- 审批人效率排行 -->
      <div class="chart-container medium">
        <div class="chart-header">
          <h3>审批人效率排行</h3>
        </div>
        <div class="chart-content" ref="approverRankingChart" style="height: 350px;"></div>
      </div>
    </div>

    <!-- 详细数据表格 -->
    <div class="data-tables">
      <el-tabs v-model="activeTab" type="card">
        <!-- 申请统计表 -->
        <el-tab-pane label="申请统计" name="applications">
          <div class="table-header">
            <h4>申请统计详情</h4>
            <el-button size="small" @click="exportTableData('applications')">
              <el-icon><Download /></el-icon>
              导出数据
            </el-button>
          </div>
          <el-table :data="applicationStats" style="width: 100%" stripe>
            <el-table-column prop="date" label="日期" width="120"></el-table-column>
            <el-table-column prop="total" label="总申请数" width="100"></el-table-column>
            <el-table-column prop="approved" label="已通过" width="100"></el-table-column>
            <el-table-column prop="rejected" label="已拒绝" width="100"></el-table-column>
            <el-table-column prop="pending" label="待审批" width="100"></el-table-column>
            <el-table-column prop="approvalRate" label="通过率" width="100">
              <template #default="{ row }">
                <el-tag :type="getApprovalRateType(row.approvalRate)">{{ row.approvalRate }}%</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="avgDuration" label="平均时长" width="120"></el-table-column>
            <el-table-column prop="efficiency" label="效率指数" width="100">
              <template #default="{ row }">
                <el-progress :percentage="row.efficiency" :stroke-width="6" :show-text="false"></el-progress>
                <span style="margin-left: 10px;">{{ row.efficiency }}%</span>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        
        <!-- 部门统计表 -->
        <el-tab-pane label="部门统计" name="departments">
          <div class="table-header">
            <h4>部门统计详情</h4>
            <el-button size="small" @click="exportTableData('departments')">
              <el-icon><Download /></el-icon>
              导出数据
            </el-button>
          </div>
          <el-table :data="departmentStats" style="width: 100%" stripe>
            <el-table-column prop="department" label="部门" width="150"></el-table-column>
            <el-table-column prop="totalApplications" label="申请总数" width="100"></el-table-column>
            <el-table-column prop="approvedApplications" label="已通过" width="100"></el-table-column>
            <el-table-column prop="rejectedApplications" label="已拒绝" width="100"></el-table-column>
            <el-table-column prop="approvalRate" label="通过率" width="100">
              <template #default="{ row }">
                <el-tag :type="getApprovalRateType(row.approvalRate)">{{ row.approvalRate }}%</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="avgProcessTime" label="平均处理时长" width="150"></el-table-column>
            <el-table-column prop="efficiency" label="部门效率" width="120">
              <template #default="{ row }">
                <el-progress :percentage="row.efficiency" :stroke-width="6" :show-text="false"></el-progress>
                <span style="margin-left: 10px;">{{ row.efficiency }}%</span>
              </template>
            </el-table-column>
            <el-table-column prop="ranking" label="效率排名" width="100">
              <template #default="{ row }">
                <el-tag :type="getRankingType(row.ranking)" size="small">第{{ row.ranking }}名</el-tag>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        
        <!-- 审批人统计表 -->
        <el-tab-pane label="审批人统计" name="approvers">
          <div class="table-header">
            <h4>审批人统计详情</h4>
            <el-button size="small" @click="exportTableData('approvers')">
              <el-icon><Download /></el-icon>
              导出数据
            </el-button>
          </div>
          <el-table :data="approverStats" style="width: 100%" stripe>
            <el-table-column prop="approver" label="审批人" width="120"></el-table-column>
            <el-table-column prop="department" label="所属部门" width="120"></el-table-column>
            <el-table-column prop="totalTasks" label="处理任务数" width="120"></el-table-column>
            <el-table-column prop="completedTasks" label="已完成" width="100"></el-table-column>
            <el-table-column prop="pendingTasks" label="待处理" width="100"></el-table-column>
            <el-table-column prop="avgResponseTime" label="平均响应时间" width="150"></el-table-column>
            <el-table-column prop="avgProcessTime" label="平均处理时间" width="150"></el-table-column>
            <el-table-column prop="efficiency" label="处理效率" width="120">
              <template #default="{ row }">
                <el-progress :percentage="row.efficiency" :stroke-width="6" :show-text="false"></el-progress>
                <span style="margin-left: 10px;">{{ row.efficiency }}%</span>
              </template>
            </el-table-column>
            <el-table-column prop="satisfaction" label="满意度" width="100">
              <template #default="{ row }">
                <el-rate v-model="row.satisfaction" disabled show-score text-color="#ff9900" score-template="{value}分"></el-rate>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </div>

    <!-- 报表生成对话框 -->
    <el-dialog
      v-model="showReportDialog"
      title="生成报表"
      width="600px"
    >
      <el-form :model="reportForm" label-width="100px">
        <el-form-item label="报表类型">
          <el-select v-model="reportForm.type" placeholder="请选择报表类型">
            <el-option label="综合统计报表" value="comprehensive"></el-option>
            <el-option label="部门效率报表" value="department"></el-option>
            <el-option label="审批人绩效报表" value="approver"></el-option>
            <el-option label="流程分析报表" value="process"></el-option>
            <el-option label="趋势分析报表" value="trend"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="时间范围">
          <el-date-picker
            v-model="reportForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            style="width: 100%;"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="报表格式">
          <el-radio-group v-model="reportForm.format">
            <el-radio label="pdf">PDF</el-radio>
            <el-radio label="excel">Excel</el-radio>
            <el-radio label="word">Word</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="包含内容">
          <el-checkbox-group v-model="reportForm.contents">
            <el-checkbox label="summary">数据摘要</el-checkbox>
            <el-checkbox label="charts">统计图表</el-checkbox>
            <el-checkbox label="tables">详细数据表</el-checkbox>
            <el-checkbox label="analysis">分析建议</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="报表名称">
          <el-input v-model="reportForm.name" placeholder="请输入报表名称"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showReportDialog = false">取消</el-button>
          <el-button type="primary" @click="confirmGenerateReport">生成报表</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import { 
  Document, Download, Files, Check, Close, TrendCharts
} from '@element-plus/icons-vue'

// 响应式数据
const timeRange = ref('month')
const customDateRange = ref([])
const trendChartType = ref('day')
const departmentChartType = ref('count')
const activeTab = ref('applications')
const showReportDialog = ref(false)

// 图表引用
const trendChart = ref(null)
const typeDistributionChart = ref(null)
const statusDistributionChart = ref(null)
const departmentChart = ref(null)
const durationChart = ref(null)
const approverRankingChart = ref(null)

// 报表表单
const reportForm = ref({
  type: 'comprehensive',
  dateRange: [],
  format: 'pdf',
  contents: ['summary', 'charts', 'tables'],
  name: ''
})

// 核心指标数据
const totalApplications = ref(1248)
const totalApplicationsChange = ref(15.2)
const approvedApplications = ref(1089)
const approvedApplicationsChange = ref(12.8)
const rejectedApplications = ref(89)
const rejectedApplicationsChange = ref(-5.3)
const approvalEfficiency = ref(87.2)
const approvalEfficiencyChange = ref(8.5)

// 申请统计数据
const applicationStats = ref([
  {
    date: '2024-01-15',
    total: 45,
    approved: 38,
    rejected: 4,
    pending: 3,
    approvalRate: 84.4,
    avgDuration: '2.3小时',
    efficiency: 88
  },
  {
    date: '2024-01-14',
    total: 52,
    approved: 46,
    rejected: 3,
    pending: 3,
    approvalRate: 88.5,
    avgDuration: '2.1小时',
    efficiency: 92
  },
  {
    date: '2024-01-13',
    total: 38,
    approved: 32,
    rejected: 5,
    pending: 1,
    approvalRate: 84.2,
    avgDuration: '2.8小时',
    efficiency: 85
  },
  {
    date: '2024-01-12',
    total: 41,
    approved: 35,
    rejected: 4,
    pending: 2,
    approvalRate: 85.4,
    avgDuration: '2.5小时',
    efficiency: 87
  },
  {
    date: '2024-01-11',
    total: 47,
    approved: 42,
    rejected: 3,
    pending: 2,
    approvalRate: 89.4,
    avgDuration: '2.0小时',
    efficiency: 94
  }
])

// 部门统计数据
const departmentStats = ref([
  {
    department: '技术部',
    totalApplications: 156,
    approvedApplications: 142,
    rejectedApplications: 8,
    approvalRate: 91.0,
    avgProcessTime: '1.8小时',
    efficiency: 94,
    ranking: 1
  },
  {
    department: '销售部',
    totalApplications: 203,
    approvedApplications: 178,
    rejectedApplications: 15,
    approvalRate: 87.7,
    avgProcessTime: '2.2小时',
    efficiency: 89,
    ranking: 2
  },
  {
    department: '市场部',
    totalApplications: 134,
    approvedApplications: 115,
    rejectedApplications: 12,
    approvalRate: 85.8,
    avgProcessTime: '2.5小时',
    efficiency: 86,
    ranking: 3
  },
  {
    department: '人事部',
    totalApplications: 89,
    approvedApplications: 76,
    rejectedApplications: 8,
    approvalRate: 85.4,
    avgProcessTime: '2.1小时',
    efficiency: 88,
    ranking: 4
  },
  {
    department: '财务部',
    totalApplications: 112,
    approvedApplications: 94,
    rejectedApplications: 11,
    approvalRate: 83.9,
    avgProcessTime: '3.2小时',
    efficiency: 82,
    ranking: 5
  }
])

// 审批人统计数据
const approverStats = ref([
  {
    approver: '张经理',
    department: '技术部',
    totalTasks: 89,
    completedTasks: 85,
    pendingTasks: 4,
    avgResponseTime: '15分钟',
    avgProcessTime: '1.2小时',
    efficiency: 95,
    satisfaction: 4.8
  },
  {
    approver: '李总监',
    department: '销售部',
    totalTasks: 76,
    completedTasks: 72,
    pendingTasks: 4,
    avgResponseTime: '22分钟',
    avgProcessTime: '1.8小时',
    efficiency: 92,
    satisfaction: 4.6
  },
  {
    approver: '王主管',
    department: '市场部',
    totalTasks: 65,
    completedTasks: 60,
    pendingTasks: 5,
    avgResponseTime: '18分钟',
    avgProcessTime: '2.1小时',
    efficiency: 89,
    satisfaction: 4.5
  },
  {
    approver: '赵经理',
    department: '人事部',
    totalTasks: 54,
    completedTasks: 51,
    pendingTasks: 3,
    avgResponseTime: '25分钟',
    avgProcessTime: '1.9小时',
    efficiency: 87,
    satisfaction: 4.4
  },
  {
    approver: '孙总监',
    department: '财务部',
    totalTasks: 43,
    completedTasks: 39,
    pendingTasks: 4,
    avgResponseTime: '35分钟',
    avgProcessTime: '2.8小时',
    efficiency: 83,
    satisfaction: 4.2
  }
])

// 方法
const getApprovalRateType = (rate) => {
  if (rate >= 90) return 'success'
  if (rate >= 80) return 'warning'
  return 'danger'
}

const getRankingType = (ranking) => {
  if (ranking <= 2) return 'success'
  if (ranking <= 4) return 'warning'
  return 'info'
}

const onTimeRangeChange = (value) => {
  console.log('时间范围变更:', value)
  // 这里可以重新加载数据
}

const onCustomDateChange = (value) => {
  console.log('自定义日期变更:', value)
  // 这里可以重新加载数据
}

const generateReport = () => {
  showReportDialog.value = true
  // 设置默认报表名称
  const now = new Date()
  const dateStr = now.toISOString().split('T')[0]
  reportForm.value.name = `审批流程统计报表_${dateStr}`
}

const confirmGenerateReport = () => {
  if (!reportForm.value.type) {
    ElMessage.warning('请选择报表类型')
    return
  }
  if (!reportForm.value.name) {
    ElMessage.warning('请输入报表名称')
    return
  }
  
  ElMessage.success('报表生成中，请稍候...')
  showReportDialog.value = false
  
  // 模拟报表生成
  setTimeout(() => {
    ElMessage.success('报表生成完成！')
  }, 2000)
}

const exportReport = () => {
  ElMessage.success('报表导出功能开发中...')
}

const exportTableData = (type) => {
  ElMessage.success(`${type}数据导出功能开发中...`)
}

// 初始化图表
const initCharts = () => {
  // 这里可以使用 ECharts 或其他图表库初始化图表
  // 由于没有引入图表库，这里只是占位
  console.log('初始化统计图表')
}

// 生命周期
onMounted(() => {
  nextTick(() => {
    initCharts()
  })
})
</script>

<style scoped>
.statistics-reports-container {
  padding: 20px;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 20px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.header-left h2 {
  margin: 0 0 5px 0;
  color: #333;
  font-size: 24px;
}

.header-left p {
  margin: 0;
  color: #666;
  font-size: 14px;
}

.time-range-section {
  margin-bottom: 20px;
  padding: 15px 20px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.range-selector {
  display: flex;
  align-items: center;
}

.key-metrics {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 20px;
  margin-bottom: 20px;
}

.metric-card {
  display: flex;
  align-items: center;
  padding: 20px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  position: relative;
}

.metric-card.total {
  border-left: 4px solid #409eff;
}

.metric-card.approved {
  border-left: 4px solid #67c23a;
}

.metric-card.rejected {
  border-left: 4px solid #f56c6c;
}

.metric-card.efficiency {
  border-left: 4px solid #e6a23c;
}

.metric-icon {
  font-size: 32px;
  margin-right: 15px;
  color: #666;
}

.metric-content {
  flex: 1;
}

.metric-number {
  font-size: 28px;
  font-weight: bold;
  color: #333;
  margin-bottom: 5px;
}

.metric-label {
  font-size: 14px;
  color: #666;
  margin-bottom: 5px;
}

.metric-change {
  font-size: 12px;
  font-weight: 600;
}

.metric-change.positive {
  color: #67c23a;
}

.metric-change.negative {
  color: #f56c6c;
}

.charts-section {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(400px, 1fr));
  gap: 20px;
  margin-bottom: 20px;
}

.chart-container {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  padding: 20px;
}

.chart-container.large {
  grid-column: span 2;
}

.chart-container.medium {
  grid-column: span 1;
}

.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.chart-header h3 {
  margin: 0;
  color: #333;
  font-size: 16px;
}

.chart-content {
  background: #f8f9fa;
  border-radius: 4px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #666;
  font-size: 14px;
}

.data-tables {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  padding: 20px;
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.table-header h4 {
  margin: 0;
  color: #333;
  font-size: 16px;
}

.dialog-footer {
  text-align: right;
}

:deep(.el-table) {
  border-radius: 0;
}

:deep(.el-table th) {
  background-color: #f8f9fa;
  color: #333;
  font-weight: 600;
}

:deep(.el-table td) {
  padding: 12px 0;
}

:deep(.el-tabs__header) {
  margin-bottom: 20px;
}

:deep(.el-tabs__content) {
  padding: 0;
}

:deep(.el-progress-bar__outer) {
  border-radius: 3px;
}

:deep(.el-rate) {
  display: flex;
  align-items: center;
}

:deep(.el-rate__text) {
  margin-left: 5px;
  font-size: 12px;
}

@media (max-width: 1200px) {
  .chart-container.large {
    grid-column: span 1;
  }
}

@media (max-width: 768px) {
  .charts-section {
    grid-template-columns: 1fr;
  }
  
  .key-metrics {
    grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  }
}
</style>